﻿using Common;
using Dm.util;
using FCT551.Base;
using FCT551.Helper;
using FCT551.Models;
using FCT551.Procedure;
using FCT551.Views;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;

namespace FCT551.ViewModels
{
    //绑定到日志方法
    public delegate void updateHandler(string msg, LogLevel level = LogLevel.Info, [CallerMemberName] string? propertyName = null);

    public delegate void updatedataHandler(int num, bool isOK);

    public delegate void UnloginHandler(object obj);

    public delegate void StartHandler(object obj);

    public delegate void FocusHandler();

    public delegate void ResetHandler(object obj);

    public delegate void EmsStopHandler(object obj);

    public class OperaViewModel : NotifyPorperChanged
    {
        private OperateView _operateView;
        private StationSatus _stationSatus;
        public static updateHandler updatemessage;
        public static FocusHandler focus;
        public static updatedataHandler updatedata;
        private CancellationTokenSource _commonIoSource;
        public static StartHandler? _Start;
        public static EmsStopHandler? EmsStop;
        public static ResetHandler _Reset;
        public static UnloginHandler _Unlogin;

        public OperaViewModel(OperateView operateView)
        {
            _stationSatus = StationSatus.空闲;
            _operateView = operateView;
            WorkStations = new ObservableCollection<NewWorkStationModel>();
            ChangeStatusCommand = new Command() { ExeAction = new Action<object>(ChangeStatus) };
            WindowLoadedCommand = new Command() { ExeAction = new Action<object>(WindowLoadedcmd) };
            WindowClosingCommand = new Command() { ExeAction = new Action<object>(WindowClosingCmd) };
            StartUpCommand = new Command() { ExeAction = new Action<object>(StartUpCmd) };
            ResetCommand = new Command() { ExeAction = new Action<object>(ResetCmd) };
            OneStepCommand = new Command() { ExeAction = new Action<object>(OneStepCmd) };
            HomeViewModel.UpdateConfigName -= ChangeNowConfigNane;
            HomeViewModel.UpdateConfigName += ChangeNowConfigNane;
            HomeViewModel._Start = StartUpCmd;
            HomeViewModel._Reset = ResetCmd;
            HomeViewModel.EmsStop = EmgStopCmd;
            TestMethods.UpdateWorkStation += UpdateWorkStation;
            HomeViewModel.InitStation += Init;
            ConfigManageViewModel.InitStation += Init;
        }

        #region 初始化命令以及属性

        private Command _changeStatusCommand;

        public Command ChangeStatusCommand
        {
            set
            {
                _changeStatusCommand = value;
            }
            get { return _changeStatusCommand; }
        }

        private Command _startupCommand;

        public Command StartUpCommand
        {
            set
            {
                _startupCommand = value;
            }
            get { return _startupCommand; }
        }

        private Command _resetCommand;

        public Command ResetCommand
        {
            set
            {
                _resetCommand = value;
            }
            get { return _resetCommand; }
        }

        private Command _onestepCommand;

        public Command OneStepCommand
        {
            set
            {
                _onestepCommand = value;
            }
            get { return _onestepCommand; }
        }

        private Command _windowLoadedCommand;

        /// <summary>
        /// 界面加载
        /// </summary>
        public Command WindowLoadedCommand
        {
            set
            {
                _windowLoadedCommand = value;
            }
            get { return _windowLoadedCommand; }
        }

        private Command _windowClosingCommand;

        /// <summary>
        /// 界面退出
        /// </summary>
        public Command WindowClosingCommand
        {
            set
            {
                _windowClosingCommand = value;
            }
            get { return _windowClosingCommand; }
        }

        private ObservableCollection<NewWorkStationModel> _workStationModels;

        public ObservableCollection<NewWorkStationModel> WorkStations
        {
            set
            {
                _workStationModels = value;
                this.SetProperty();
            }
            get { return _workStationModels; }
        }

        private string _configname = "";

        public string NowConfigName
        {
            set
            {
                _configname = value;
                this.SetProperty();
            }
            get { return _configname; }
        }

        private string _allqrcode;

        public string AllQrCode
        {
            set
            {
                _allqrcode = value;
                this.SetProperty();
            }
            get { return _allqrcode; }
        }

        private SolidColorBrush _resultcolor = _grayBrush;

        public SolidColorBrush ResultColor
        {
            set
            {
                _resultcolor = value;
                this.SetProperty();
            }
            get { return _resultcolor; }
        }

        private string _resultmsg = "待测";

        public string ResultMsg
        {
            set
            {
                _resultmsg = value;
                this.SetProperty();
            }
            get { return _resultmsg; }
        }

        #endregion 初始化命令以及属性

        #region 绑定方法

        /// <summary>
        /// 单步执行方法
        /// </summary>
        /// <param name="obj"></param>
        private async void OneStepCmd(object obj)
        {
        }

        /// <summary>
        /// 急停方法
        /// </summary>
        /// <param name="obj"></param>
        public async void EmgStopCmd(object obj)
        {
            Global._isEmg = true;
            _stationSatus = StationSatus.停止;
            await Task.Run(() =>
            {
                Global._EmgStopTokenSource.Cancel();
                IoMotion.MotionStop();
                //气缸停止
                IoMotion.MotionAirStop();
                //pwm断开
                //IoMotion.OffAllPwm();
                //IO断开
                Global._PqwIoCommon.SetDo((int)CommonIODefineDo.供电12v, false);
                Global._isRunning = false;
                IoMotion.Error(1000);
                UpdateMessage("设备急停！", LogLevel.Error);
            });
            await Application.Current.Dispatcher.BeginInvoke(() =>
            {
                ResultColor = _redBrush;
                ResultMsg = "急停中";
            });
        }

        /// <summary>
        /// 复位方法
        /// </summary>
        /// <param name="obj"></param>
        public async void ResetCmd(object obj)
        {
            if (Global._isRunning)
            {
                UpdateMessage("设备正在运行，无法复位！", LogLevel.Error);
                return;
            }
            if (isSafeDoor || isSafeSunShine)
            {
                UpdateMessage("安全光幕或者安全门被启动，请关闭安全门或者离开安全光幕感应区！", LogLevel.Error);
                return;
            }
            try
            {
                //if (Global._User.UserLevel < 2)
                //{
                //    UpdateMessage("权限不够，请联系对应人员", LogLevel.Error);
                //    return;
                //}
                await Task.Run(async () =>
                {
                    Global._PqwIoCommon.GetDi();
                    if (!Global._PqwIoCommon.GetDi((int)CommonIODefineDi.急停))
                    {
                        UpdateMessage("急停按钮被按下，无法复位！", LogLevel.Error);
                        return;
                    }

                    Global._isRunning = false;
                    Global._isEmg = false;
                    Global._EmgStopTokenSource = new CancellationTokenSource();
                    IoMotion.MotionStop();
                    //pwm断开
                    IoMotion.OffAllPwm();
                    //IO断开
                    Global._PqwIoCommon.SetDo((int)CommonIODefineDo.供电12v, false);
                    //气缸复位
                    await IoMotion.MotionAirOut(3000);
                    IoMotion.OK();
                    UpdateMessage("设备复位！");
                    await Application.Current.Dispatcher.InvokeAsync(() =>
                    {
                        ResultColor = _grayBrush;
                        ResultMsg = "待测";
                        // Init();
                    });
                    _stationSatus = StationSatus.空闲;
                });
            }
            catch (Exception e)
            {
                UpdateMessage(e.Message, LogLevel.Error);
            }
        }

        /// <summary>
        /// 16路转化id，对应到实际工位
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private int StationIdConver16(int id)
        {
            switch (id)
            {
                case 1:
                    return 13;

                case 2:
                    return 14;

                case 3:
                    return 15;

                case 4:
                    return 16;

                case 5:
                    return 9;

                case 6:
                    return 10;

                case 7:
                    return 11;

                case 8:
                    return 12;

                case 9:
                    return 5;

                case 10:
                    return 6;

                case 11:
                    return 7;

                case 12:
                    return 8;

                case 13:
                    return 1;

                case 14:
                    return 2;

                case 15:
                    return 3;

                case 16:
                    return 4;
            }

            return id;
        }

        /// <summary>
        /// 20路转化id，对应到实际工位
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private int StationIdConver20(int id)
        {
            switch (id)
            {
                case 1:
                    return 17;

                case 2:
                    return 18;

                case 3:
                    return 19;

                case 4:
                    return 20;

                case 5:
                    return 13;

                case 6:
                    return 14;

                case 7:
                    return 15;

                case 8:
                    return 16;

                case 9:
                    return 9;

                case 10:
                    return 10;

                case 11:
                    return 11;

                case 12:
                    return 12;

                case 13:
                    return 5;

                case 14:
                    return 6;

                case 15:
                    return 7;

                case 16:
                    return 8;

                case 17:
                    return 1;

                case 18:
                    return 2;

                case 19:
                    return 3;

                case 20:
                    return 4;
            }

            return id;
        }

        /// <summary>
        /// 12路转化id，对应到实际工位
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private int StationIdConver12(int id)
        {
            switch (id)
            {
                case 1:
                    return 9;

                case 2:
                    return 10;

                case 3:
                    return 11;

                case 4:
                    return 12;

                case 5:
                    return 5;

                case 6:
                    return 6;

                case 7:
                    return 7;

                case 8:
                    return 8;

                case 9:
                    return 1;

                case 10:
                    return 2;

                case 11:
                    return 3;

                case 12:
                    return 4;

                case 13:
                    return 5;

                case 14:
                    return 6;

                case 15:
                    return 7;

                case 16:
                    return 8;

                case 17:
                    return 1;

                case 18:
                    return 2;

                case 19:
                    return 3;

                case 20:
                    return 4;
            }

            return id;
        }

        /// <summary>
        /// 启动方法
        /// </summary>
        /// <param name="obj"></param>
        public void StartUpCmd(object obj)
        {
            Task.Run(async () =>
            {
                if (Global._isInit)
                {
                    if (Global._isIOdebug)
                    {
                        return;
                    }
                    if (isSafeDoor || isSafeSunShine)
                    {
                        UpdateMessage("安全光幕或者安全门被启动，请关闭安全门或者离开安全光幕感应区！", LogLevel.Error);
                        return;
                    }
                    if (Global._WorkStationName == "" && Global._WorkStationOrderName == "")
                    {
                        UpdateMessage("站号和工单为空，请选择对应站号和工单", LogLevel.Error);
                        return;
                    }
                    UpdateMessage("开始自动启动！");
                    try
                    {
                        while (true)
                        {
                            if (!_commonIoSource.Token.IsCancellationRequested)
                            {
                                try
                                {
                                    if (Global._Lisence)
                                    {
                                        UpdateMessage("证书已过期，请联系厂商！", LogLevel.Error);
                                        return;
                                    }

                                    if (_stationSatus == StationSatus.停止 || _stationSatus == StationSatus.运行)
                                    {
                                        Global._isRunning = false;
                                        UpdateMessage("机台急停或正在运行！", LogLevel.Error);
                                        break;
                                    }

                                    if (!Global.ClientISConnect)
                                    {
                                        Global._isRunning = false;
                                        UpdateMessage("与扫码机通信异常！退出自动流程", LogLevel.Error);
                                        break;
                                    }
                                    await Global.client.SendMessagesAsync("1");
                                    string reinfo = await Global.client.ReceiveRes();
                                    if (reinfo != "1")
                                    {
                                        Global._isRunning = false;
                                        UpdateMessage("与扫码机通信异常！退出自动流程", LogLevel.Error);
                                        break;
                                    }
                                    Global._isRunning = true;

                                    //检测结果
                                    bool Result = true;
                                    //进板状态
                                    bool OperaStatus = true;
                                    _stationSatus = StationSatus.运行;
                                    var token = Global._EmgStopTokenSource.Token;
                                    token.ThrowIfCancellationRequested(); // 检查急停
                                    if (isSafeDoor || isSafeSunShine)
                                    {
                                        Global._isRunning = false;
                                        UpdateMessage("安全光幕或者安全门被启动，请关闭安全门或者离开安全光幕感应区！", LogLevel.Error);
                                        EmgStopCmd(null);
                                        break;
                                    }
                                    Global._PqwIoCommon.GetDi();
                                    if (Global._PqwIoCommon.GetDi((int)CommonIODefineDi.到位))
                                    {
                                        //存在多余的板子，报警

                                        Global._isRunning = false;
                                        UpdateMessage("此刻有板在机台内，急停报警！！！！", LogLevel.Error);
                                        EmgStopCmd(null);
                                        break;
                                    }
                                    token.ThrowIfCancellationRequested(); // 检查急停
                                    string Code = "";
                                    UpdateMessage("就绪，等待扫码机反馈！");
                                    await Global.client.SendMessagesAsync("need");
                                    string msg = await Global.client.ReceiveRes();
                                    if (msg == "就绪")
                                    {
                                        token.ThrowIfCancellationRequested(); // 检查急停
                                        UpdateMessage("扫码机就绪！");
                                        //更新二维码
                                        await Global.client.SendMessagesAsync("code");
                                        Code = await Global.client.ReceiveRes();
                                        //进板操作
                                        token.ThrowIfCancellationRequested(); // 检查急停
                                        OperaStatus = await IoMotion.MotionIn();
                                    }
                                    else
                                    {
                                        //轮询发送信号，持续等待
                                        while (true)
                                        {
                                            if (!_commonIoSource.Token.IsCancellationRequested)
                                            {
                                                token.ThrowIfCancellationRequested(); // 检查急停
                                                await Global.client.SendMessagesAsync("need");
                                                string Remsg = await Global.client.ReceiveRes();
                                                if (Remsg == "就绪")
                                                {
                                                    UpdateMessage("扫码机就绪！");
                                                    //更新二维码
                                                    await Global.client.SendMessagesAsync("code");
                                                    Code = await Global.client.ReceiveRes();
                                                    //进板操作
                                                    token.ThrowIfCancellationRequested(); // 检查急停
                                                    OperaStatus = await IoMotion.MotionIn();
                                                    break;
                                                }
                                            }
                                            else
                                            {
                                                //线程被取消，退出线程
                                                break;
                                            }

                                            await Task.Delay(100);
                                        }
                                    }
                                    if (_commonIoSource.Token.IsCancellationRequested)
                                    {
                                        _stationSatus = StationSatus.空闲;
                                        Global._isRunning = false;
                                        //线程被取消，退出线程
                                        UpdateMessage("退出自动流程", LogLevel.Error);
                                        break;
                                    }
                                    // UI操作通过Dispatcher
                                    await Application.Current.Dispatcher.InvokeAsync(() =>
                                    {
                                        ResultColor = _grayBrush;
                                        ResultMsg = "正在测试";
                                        Init(); // 确保Init内部没有阻塞操作
                                    });

                                    token.ThrowIfCancellationRequested(); // 检查急停
                                                                          //判断进板是否成功
                                    if (!OperaStatus)
                                    {
                                        Global._isRunning = false;
                                        UpdateMessage("进板异常！设备急停", LogLevel.Error);
                                        EmgStopCmd(null);
                                        break;
                                    }
                                    UpdateMessage("进板正常！");
                                    token.ThrowIfCancellationRequested(); // 检查急停
                                                                          //操作前检查是否有多余板子尽量
                                    Global._PqwIoCommon.GetDi();
                                    if (Global._PqwIoCommon.GetDi((int)CommonIODefineDi.进板))
                                    {
                                        //存在多余的板子，报警

                                        Global._isRunning = false;
                                        UpdateMessage("检测到多个产品在机台内，急停报警！！！！", LogLevel.Error);
                                        EmgStopCmd(null);
                                        break;
                                    }
                                    token.ThrowIfCancellationRequested(); // 检查急停
                                    //判断二维码
                                    if (Code == "")
                                    {
                                        Global._isRunning = false;
                                        UpdateMessage("二维码异常！设备急停", LogLevel.Error);
                                        EmgStopCmd(null);
                                        break;
                                    }
                                    UpdateMessage("二维码正常！");
                                    //进板气缸操作
                                    if (!await IoMotion.MotionAirIn())
                                    {
                                        Global._isRunning = false;
                                        UpdateMessage("进板气缸异常！设备急停", LogLevel.Error);
                                        EmgStopCmd(null);
                                        break;
                                    }
                                    UpdateMessage("进板气缸正常！");
                                    token.ThrowIfCancellationRequested(); // 检查急停
                                                                          //分配二维码
                                    string[] AllWorkStations = Code.Split(';');
                                    UpdateMessage($"工位数量：{AllWorkStations.Length}");
                                    await Application.Current.Dispatcher.InvokeAsync(() =>
                                    {
                                        foreach (var item in AllWorkStations)
                                        {
                                            token.ThrowIfCancellationRequested(); // 检查急停
                                            string[] strings = item.Split(",");
                                            int station = Convert.ToInt32(strings[0].Remove(0, 2));
                                            string code = strings[1];

                                            if (Global._Config.MaxStationNums == 16)
                                            {
                                                int finlStation = StationIdConver16(station);
                                                UpdateMessage($"{station}工位检测到，转化后工位{finlStation}");
                                                WorkStations.Where(s => s.StationTestId == finlStation).ToList().ForEach(s =>
                                                {
                                                    s.IsExecute = true;
                                                    s.Code = code;
                                                });
                                            }
                                            else if (Global._Config.MaxStationNums == 20)
                                            {
                                                int finlStation = StationIdConver20(station);
                                                UpdateMessage($"{station}工位检测到，转化后工位{finlStation}");
                                                WorkStations.Where(s => s.StationTestId == finlStation).ToList().ForEach(s =>
                                                {
                                                    s.IsExecute = true;
                                                    s.Code = code;
                                                });
                                            }
                                            else if (Global._Config.MaxStationNums == 12)
                                            {
                                                int finlStation = StationIdConver12(station);
                                                UpdateMessage($"{station}工位检测到，转化后工位{finlStation}");
                                                WorkStations.Where(s => s.StationTestId == finlStation).ToList().ForEach(s =>
                                                {
                                                    s.IsExecute = true;
                                                    s.Code = code;
                                                });
                                            }
                                        }
                                        WorkStations.Where(s => s.IsExecute == false).ToList().ForEach(s =>
                                        {
                                            s.Result = "该工位二维码丢失！";
                                            s.ResultColor = _redBrush;
                                        });
                                    });

                                    //选择好执行的工位
                                    //var ExeWorkStation = WorkStations.AsParallel().Where(s =>s.IsExecute == true).ToList();
                                    var ExeWorkStation = WorkStations.ToList();
                                    //正常检测
                                    for (int i = 0; i < Global._ProduceConfigs.Count; i++)
                                    {
                                        token.ThrowIfCancellationRequested(); // 检查急停
                                        if (!Global._ProduceConfigs[i].IsTest) { continue; }
                                        //打开IO
                                        UpdateMessage("测试项" + Global._ProduceConfigs[i].Id + "开始检测");
                                        Global._PqwIoCommon.SetDo((int)CommonIODefineDo.供电12v, true);
                                        token.ThrowIfCancellationRequested(); // 检查急停
                                        await Task.Delay(10);
                                        //打开PWM输出
                                        token.ThrowIfCancellationRequested(); // 检查急停
                                        TestMethods.SetALLPwmValue(Global._ProduceConfigs[i]);
                                        token.ThrowIfCancellationRequested(); // 检查急停
                                        await Task.Delay(500);
                                        token.ThrowIfCancellationRequested(); // 检查急停
                                                                              //采集电压电流
                                        await TestMethods.GetVoltageandCurrent(Global._ProduceConfigs[i]);
                                        token.ThrowIfCancellationRequested(); // 检查急停
                                                                              //关闭pwm输出
                                        TestMethods.CloseALLPwmValue(Global._ProduceConfigs[i]);
                                        token.ThrowIfCancellationRequested(); // 检查急停
                                        //await Task.Delay(10);
                                        //关闭IO
                                        token.ThrowIfCancellationRequested(); // 检查急停
                                        Global._PqwIoCommon.SetDo((int)CommonIODefineDo.供电12v, false);
                                        token.ThrowIfCancellationRequested(); // 检查急停
                                        for (int j = 0; j < ExeWorkStation.Count; j++)
                                        {
                                            token.ThrowIfCancellationRequested(); // 检查急停
                                                                                  //测量电压数量
                                            bool RotateSpeedRes = TestMethods.GetRotateSpeedValue(ExeWorkStation[j].StationTestId, Global._ProduceConfigs[i], out double RotateSpeedvalue);
                                            //测量电流
                                            bool CurrentRes = TestMethods.GetCurrentValue(ExeWorkStation[j].StationTestId, Global._ProduceConfigs[i], out double Currentvalue);
                                            //string ShowRotateSpeedRes = RotateSpeedRes ? "转速OK" : RotateSpeedvalue.ToString() + "(NG)";
                                            string ShowRotateSpeedRes = RotateSpeedRes ? "转速OK" : "转速NG";
                                            string ShowCurrentRes = CurrentRes ? Currentvalue.ToString() + "A" : Currentvalue.ToString() + "A" + "(NG)";

                                            if (!RotateSpeedRes || !CurrentRes)
                                            {
                                                ExeWorkStation[j].ResultColor = _redBrush;
                                                ExeWorkStation[j].StationTestRes = false;
                                                ExeWorkStation[j].Result = "NG";
                                                Result = false;
                                            }
                                            else
                                            {
                                                ExeWorkStation[j].ResultColor = _greenBrush;
                                                ExeWorkStation[j].StationTestRes = true;
                                                ExeWorkStation[j].Result = "OK";
                                            }
                                            switch (i + 1)
                                            {
                                                case 1:
                                                    ExeWorkStation[j].Test1 = "1档:" + ShowRotateSpeedRes + "," + ShowCurrentRes;
                                                    break;

                                                case 2:
                                                    ExeWorkStation[j].Test2 = "2档:" + ShowRotateSpeedRes + "," + ShowCurrentRes;
                                                    break;

                                                case 3:
                                                    ExeWorkStation[j].Test3 = "3档:" + ShowRotateSpeedRes + "," + ShowCurrentRes;
                                                    break;

                                                default:
                                                    break;
                                            }
                                        }
                                    }
                                    //复测判断
                                    if (!Result)
                                    {
                                        //当出现NG以后判断是否需要复测
                                        //是否复测
                                        if (Global._Config.IsNGReTest)
                                        {
                                            //重新执行气缸动作
                                            //上气缸上升
                                            await IoMotion.TopAirUp(3000);
                                            //上气缸下降
                                            await IoMotion.TopAirDown(3000);
                                            //await Task.Delay(1000);
                                            //确认复测,重新执行所有工位
                                            //执行产品配置
                                            UpdateMessage("进入复测！");
                                            Result = true;
                                            for (int i = 0; i < Global._ProduceConfigs.Count; i++)
                                            {
                                                token.ThrowIfCancellationRequested(); // 检查急停
                                                if (!Global._ProduceConfigs[i].IsTest) { continue; }
                                                //打开IO
                                                Global._PqwIoCommon.SetDo((int)CommonIODefineDo.供电12v, true);
                                                token.ThrowIfCancellationRequested(); // 检查急停
                                                await Task.Delay(100);
                                                //打开PWM输出
                                                token.ThrowIfCancellationRequested(); // 检查急停
                                                TestMethods.SetALLPwmValue(Global._ProduceConfigs[i]);
                                                token.ThrowIfCancellationRequested(); // 检查急停
                                                await Task.Delay(2500);
                                                token.ThrowIfCancellationRequested(); // 检查急停
                                                                                      //采集电压电流
                                                await TestMethods.GetVoltageandCurrent(Global._ProduceConfigs[i]);
                                                token.ThrowIfCancellationRequested(); // 检查急停
                                                                                      //关闭pwm输出

                                                TestMethods.CloseALLPwmValue(Global._ProduceConfigs[i]);
                                                token.ThrowIfCancellationRequested(); // 检查急停
                                                await Task.Delay(100);
                                                //关闭IO
                                                token.ThrowIfCancellationRequested(); // 检查急停
                                                Global._PqwIoCommon.SetDo((int)CommonIODefineDo.供电12v, false);
                                                token.ThrowIfCancellationRequested(); // 检查急停
                                                for (int j = 0; j < ExeWorkStation.Count; j++)
                                                {
                                                    token.ThrowIfCancellationRequested(); // 检查急停
                                                                                          //测量电压数量
                                                    bool RotateSpeedRes = TestMethods.GetRotateSpeedValue(ExeWorkStation[j].StationTestId, Global._ProduceConfigs[i], out double RotateSpeedvalue);
                                                    //测量电流
                                                    bool CurrentRes = TestMethods.GetCurrentValue(ExeWorkStation[j].StationTestId, Global._ProduceConfigs[i], out double Currentvalue);
                                                    string ShowRotateSpeedRes = RotateSpeedRes ? "转速OK" : "转速NG";
                                                    string ShowCurrentRes = CurrentRes ? Currentvalue.ToString() + "A" : Currentvalue.ToString() + "A" + "(NG)";

                                                    if (!RotateSpeedRes || !CurrentRes)
                                                    {
                                                        ExeWorkStation[j].ResultColor = _redBrush;
                                                        ExeWorkStation[j].StationTestRes = false;
                                                        ExeWorkStation[j].Result = "NG";

                                                        Result = false;
                                                    }
                                                    else
                                                    {
                                                        ExeWorkStation[j].ResultColor = _greenBrush;
                                                        ExeWorkStation[j].StationTestRes = true;
                                                        ExeWorkStation[j].Result = "OK";
                                                    }
                                                    switch (i + 1)
                                                    {
                                                        case 1:
                                                            ExeWorkStation[j].Test1 = "1档:" + ShowRotateSpeedRes + "," + ShowCurrentRes;
                                                            break;

                                                        case 2:
                                                            ExeWorkStation[j].Test2 = "2档:" + ShowRotateSpeedRes + "," + ShowCurrentRes;
                                                            break;

                                                        case 3:
                                                            ExeWorkStation[j].Test3 = "3档:" + ShowRotateSpeedRes + "," + ShowCurrentRes;
                                                            break;

                                                        default:
                                                            break;
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    //更新工位状态
                                    await Application.Current.Dispatcher.InvokeAsync(() =>
                                    {
                                        for (int i = 0; i < ExeWorkStation.Count; i++)
                                        {
                                            token.ThrowIfCancellationRequested(); // 检查急停

                                            WorkStations.AsParallel().Where(s => s.StationTestId == ExeWorkStation[i].StationTestId).ForAll(s =>
                                            {
                                                s.Test1 = ExeWorkStation[i].Test1;
                                                s.Test2 = ExeWorkStation[i].Test2;
                                                s.Test3 = ExeWorkStation[i].Test3;
                                                s.Result = ExeWorkStation[i].IsExecute ? ExeWorkStation[i].Result : ExeWorkStation[i].Result == "OK" ? "二维码丢失！检测OK" : "二维码丢失！检测NG";
                                                s.ResultColor = ExeWorkStation[i].IsExecute ? ExeWorkStation[i].ResultColor : ExeWorkStation[i].Result == "OK" ? _yelloBrush : _redBrush;
                                                s.StationTestRes = ExeWorkStation[i].StationTestRes;
                                            });
                                        }
                                        if (Result)
                                        {
                                            ResultColor = _greenBrush;
                                            ResultMsg = "OK";
                                        }
                                        else
                                        {
                                            ResultColor = _redBrush;
                                            ResultMsg = "NG";
                                        }
                                    });
                                    UpdateMessage("检测完毕！");

                                    token.ThrowIfCancellationRequested(); // 检查急停
                                    string name = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");
                                    string name1 = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-电流");
                                    string name2 = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-电压");
                                    FileWriteHelper.WriteToFile(ExeWorkStation, name);
                                    //输出CSV文件，和测试报告一个路径
                                    Dictionary<string, List<double>> Currentdic = new();
                                    Dictionary<string, List<double>> Voltagedic = new();
                                    int index = 0;
                                    for (int i = 0; i < ExeWorkStation.Count; i++)
                                    {
                                        Currentdic.Add(ExeWorkStation[i].Code + "——" + index.toString(), TestMethods.CurrentDic[ExeWorkStation[i].StationTestId - 1]);
                                        Voltagedic.Add(ExeWorkStation[i].Code + "——" + index.toString(), TestMethods.VoltageDic[ExeWorkStation[i].StationTestId - 1]);
                                        index++;
                                    }
                                    FileWriteHelper.WriteToCsv(Currentdic, name1);
                                    FileWriteHelper.WriteToCsv(Voltagedic, name2);
                                    UpdateMessage("测试文件输出完毕！");
                                    token.ThrowIfCancellationRequested(); // 检查急停
                                                                          //检查是否有二维码丢失的工位
                                                                          //var NGExeWorkStation = WorkStations.AsParallel().Where(s => s.IsExecute == false).ToList();
                                                                          //if (NGExeWorkStation.Count > 0)
                                                                          //{
                                                                          //    Global._isRunning = false;
                                                                          //    UpdateMessage("存在二维码丢失，急停报警！！！！", LogLevel.Error);
                                                                          //    EmgStopCmd(null);
                                                                          //    break;
                                                                          //}
                                    token.ThrowIfCancellationRequested(); // 检查急停//检测完毕，出板气缸操作
                                    bool MesRes = true;
                                    string mesresult = Result ? "PASS" : "FALSE";    //输出测试报告+上传Mes

                                    if (Global._Config.IsMes)
                                    {
                                        if (Result)
                                        {
                                            //ok正常上传
                                            //mes上传
                                            if (true)
                                            {
                                                //上传MES
                                                string SN = "";
                                                for (int i = 0; i < ExeWorkStation.Count; i++)
                                                {
                                                    if (!ExeWorkStation[i].IsExecute) { continue; }
                                                    SN += ExeWorkStation[i].Code + "," + ExeWorkStation[i].StationTestRes.ToString() + "," + ExeWorkStation[i].Result + "," + ExeWorkStation[i].Name + ";";
                                                }
                                                SN = SN.Remove(SN.Length - 1, 1);
                                                MyLog.Info("请求数据：" + SN);
                                                //检查SN
                                                var ResSN = await Global._MESServiceClient.CheckRouteAsync(Global._WorkStationOrderName, SN, Global._WorkStationName, "001");
                                                if (ResSN.IsSuccess)
                                                {
                                                    //掉过站接口
                                                    UpdateMessage("SN校验成功！");
                                                    var ResPass = await Global._MESServiceClient.PassTerminalAsync(Global._WorkStationOrderName, SN, Global._WorkStationName, mesresult, "001");
                                                    if (!ResPass.IsSuccess)
                                                    {
                                                        MesRes = false;
                                                        UpdateMessage("过站失败！反馈信息：" + ResPass.Message, LogLevel.Error);
                                                    }
                                                    else
                                                    {
                                                        UpdateMessage("过站成功！" + ResPass.Message);
                                                    }
                                                }
                                                else
                                                {
                                                    MesRes = false;
                                                    UpdateMessage("SN检验失败！反馈信息：" + ResSN.Message, LogLevel.Error);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            //NG 弹窗询问
                                            if (Global._Config.IsNGToMes)
                                            {
                                                //询问是否上传
                                                bool reslue = MessageBox.Show("NG！请确认是否上传mes！", "确认", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes;
                                                if (reslue)
                                                {
                                                    //mes上传
                                                    if (true)
                                                    {
                                                        //上传MES
                                                        string SN = "";
                                                        for (int i = 0; i < ExeWorkStation.Count; i++)
                                                        {
                                                            if (!ExeWorkStation[i].IsExecute) { continue; }
                                                            SN += ExeWorkStation[i].Code + "," + ExeWorkStation[i].StationTestRes.ToString() + "," + ExeWorkStation[i].Result + "," + ExeWorkStation[i].Name + ";";
                                                        }
                                                        SN = SN.Remove(SN.Length - 1, 1);
                                                        MyLog.Info("请求数据：" + SN);
                                                        //检查SN
                                                        var ResSN = await Global._MESServiceClient.CheckRouteAsync(Global._WorkStationOrderName, SN, Global._WorkStationName, "001");
                                                        if (ResSN.IsSuccess)
                                                        {
                                                            //掉过站接口
                                                            UpdateMessage("SN校验成功！");
                                                            var ResPass = await Global._MESServiceClient.PassTerminalAsync(Global._WorkStationOrderName, SN, Global._WorkStationName, mesresult, "001");
                                                            if (!ResPass.IsSuccess)
                                                            {
                                                                MesRes = false;
                                                                UpdateMessage("过站失败！反馈信息：" + ResPass.Message, LogLevel.Error);
                                                            }
                                                            else
                                                            {
                                                                UpdateMessage("过站成功！" + ResPass.Message);
                                                            }
                                                        }
                                                        else
                                                        {
                                                            MesRes = false;
                                                            UpdateMessage("SN检验失败！反馈信息：" + ResSN.Message, LogLevel.Error);
                                                        }
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                //没有询问，直接上传
                                                //mes上传
                                                if (true)
                                                {
                                                    //上传MES
                                                    string SN = "";
                                                    for (int i = 0; i < ExeWorkStation.Count; i++)
                                                    {
                                                        if (!ExeWorkStation[i].IsExecute) { continue; }
                                                        SN += ExeWorkStation[i].Code + "," + ExeWorkStation[i].StationTestRes.ToString() + "," + ExeWorkStation[i].Result + "," + ExeWorkStation[i].Name + ";";
                                                    }
                                                    SN = SN.Remove(SN.Length - 1, 1);
                                                    MyLog.Info("请求数据：" + SN);
                                                    //检查SN
                                                    var ResSN = await Global._MESServiceClient.CheckRouteAsync(Global._WorkStationOrderName, SN, Global._WorkStationName, "001");
                                                    if (ResSN.IsSuccess)
                                                    {
                                                        //掉过站接口
                                                        UpdateMessage("SN校验成功！");
                                                        var ResPass = await Global._MESServiceClient.PassTerminalAsync(Global._WorkStationOrderName, SN, Global._WorkStationName, mesresult, "001");
                                                        if (!ResPass.IsSuccess)
                                                        {
                                                            MesRes = false;
                                                            UpdateMessage("过站失败！反馈信息：" + ResPass.Message, LogLevel.Error);
                                                        }
                                                        else
                                                        {
                                                            UpdateMessage("过站成功！" + ResPass.Message);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        MesRes = false;
                                                        UpdateMessage("SN检验失败！反馈信息：" + ResSN.Message, LogLevel.Error);
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    if (!MesRes)
                                    {
                                        Global._isRunning = false;
                                        UpdateMessage("Mes上传失败，急停报警！！！！", LogLevel.Error);
                                        EmgStopCmd(null);
                                        break;
                                    }

                                    //产能更新
                                    if (Result)
                                    {
                                        int nums = ExeWorkStation.Where(s => s.StationTestRes == Result).ToList().Count;
                                        //产能，饼状图更新
                                        SqlSugarHelper.SqlWrite(nums, Result);
                                        //写总表
                                        SqlSugarHelper.SqlWriteByYear("ALLcapacity", nums, Result);
                                        //写月表
                                        SqlSugarHelper.SqlWriteByYear(DateTime.Now.Year.ToString() + "capacity", nums, Result);
                                        UpdateDates(nums, Result);
                                    }
                                    else
                                    {
                                        //NG里面有OK的
                                        int oknums = ExeWorkStation.Where(s => s.StationTestRes == true).ToList().Count;
                                        int ngnums = ExeWorkStation.Where(s => s.StationTestRes == false).ToList().Count;
                                        SqlSugarHelper.SqlWrite(oknums, true);
                                        SqlSugarHelper.SqlWrite(ngnums, false);
                                        //写总表
                                        SqlSugarHelper.SqlWriteByYear("ALLcapacity", oknums, true);
                                        //写月表
                                        SqlSugarHelper.SqlWriteByYear(DateTime.Now.Year.ToString() + "capacity", oknums, true);
                                        //产能，饼状图更新
                                        UpdateDates(oknums, true);
                                        UpdateDates(ngnums, false);
                                        //报警
                                        IoMotion.Error(1000);
                                    }
                                    UpdateMessage("产能更新完毕！");
                                    token.ThrowIfCancellationRequested(); // 检查急停
                                    //NG报警停机
                                    if (!Result)
                                    {
                                        Global._isRunning = false;
                                        UpdateMessage("产品NG，急停报警！！！！", LogLevel.Error);
                                        EmgStopCmd(null);
                                        break;
                                    }
                                    token.ThrowIfCancellationRequested(); // 检查急停
                                                                          //Mes失败报警停机

                                    //if (!await IoMotion.MotionAirOut(3000))
                                    //{
                                    //    Global._isRunning = false;
                                    //    UpdateMessage("出板气缸操作异常！设备急停", LogLevel.Error);
                                    //    break;
                                    //}
                                    await IoMotion.MotionAirOut(2000);
                                    UpdateMessage("出板气缸正常！");
                                    token.ThrowIfCancellationRequested(); // 检查急停
                                                                          //等待下游要料
                                    UpdateMessage("等待下游要料！");
                                    bool isOutOK = true;
                                    while (true)
                                    {
                                        if (!_commonIoSource.Token.IsCancellationRequested)
                                        {
                                            token.ThrowIfCancellationRequested(); // 检查急停
                                            Global._PqwIoCommon.GetDi();
                                            if (Global._PqwIoCommon.GetDi((int)CommonIODefineDi.下游要料))
                                            {
                                                UpdateMessage("下游要料！");
                                                if (!await IoMotion.MotionOut())
                                                {
                                                    isOutOK = false;
                                                    Global._isRunning = false;
                                                    UpdateMessage("出板操作异常！设备急停", LogLevel.Error);
                                                    break;
                                                }
                                                break;
                                            }
                                        }
                                        else
                                        {
                                            //线程被取消，退出线程
                                            break;
                                        }

                                        await Task.Delay(100);
                                    }
                                    if (!isOutOK)
                                    {
                                        UpdateMessage("出板异常！设备急停！", LogLevel.Error);
                                        Global._isRunning = false;
                                        break;
                                    }
                                    UpdateMessage("出板正常！");
                                    _stationSatus = StationSatus.空闲;
                                }
                                catch (Exception e)
                                {
                                    IoMotion.MotionStop();
                                    Global._isRunning = false;
                                    _stationSatus = StationSatus.停止;
                                    IoMotion.MotionAirStop();
                                    UpdateMessage(e.Message, LogLevel.Error);
                                    IoMotion.Error(1000);
                                    break;
                                }
                            }
                            else
                            {
                                //线程被取消，退出线程
                                break;
                            }

                            await Task.Delay(10, _commonIoSource.Token);
                        }
                    }
                    catch (Exception e)
                    {
                        IoMotion.MotionStop();
                        Global._isRunning = false;
                        _stationSatus = StationSatus.停止;
                        IoMotion.MotionAirStop();
                        UpdateMessage(e.Message, LogLevel.Error);
                        IoMotion.Error(2000);
                    }
                }
                else
                {
                    UpdateMessage("请初始化！！", LogLevel.Error);
                }
            }, _commonIoSource.Token);
        }

        /// <summary>
        /// 更新数据
        /// </summary>
        public void UpdateDates(int num, bool res)
        {
            Application.Current.Dispatcher.BeginInvoke(() =>
            {
                updatedata.Invoke(num, res);
            });
        }

        // 避免重复创建Brush对象
        private static readonly SolidColorBrush _greenBrush = new SolidColorBrush(Colors.Green);

        private static readonly SolidColorBrush _yelloBrush = new SolidColorBrush(Colors.Yellow);
        private static readonly SolidColorBrush _redBrush = new SolidColorBrush(Colors.Red);
        private static readonly SolidColorBrush _blackBrush = new SolidColorBrush(Colors.Black);
        private static readonly SolidColorBrush _transparentBrush = new SolidColorBrush(Colors.Transparent);
        private static readonly SolidColorBrush _whiteBrush = new SolidColorBrush(Colors.White);
        private static readonly SolidColorBrush _grayBrush = new SolidColorBrush(Colors.Gray);
        private bool isSafeSunShine = false;//安全光幕是否触发
        private bool isSafeDoor = false;//安全光幕是否触发

        /// <summary>
        /// 更新读取到的值
        /// </summary>
        /// <param name="id"></param>
        /// <param name="v1"></param>
        /// <param name="v2"></param>
        /// <param name="v3"></param>
        public void UpdateWorkStation(int id, string v1, string v2, string v3, bool res)
        {
        }

        /// <summary>
        /// 界面加载的时候使用的方法
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void WindowLoadedcmd(object obj)
        {
            _Unlogin?.Invoke(null);
            _commonIoSource = new CancellationTokenSource();
            //退出登录
            if (Global._Config == null)
            {
                NowConfigName = "暂无配置！";
            }
            else
            {
                NowConfigName = Global._Config.ConfigName;
                if (Global._WorkStationName != "" && Global._WorkStationOrderName != "")
                {
                    NowConfigName += "，当前站名：" + Global._WorkStationName + ",当前工单：" + Global._WorkStationOrderName;
                }
            }
            Task.Run(new Action(async () =>
            {
                try
                {
                    while (true)
                    {
                        try
                        {
                            if (!_commonIoSource.Token.IsCancellationRequested)
                            {
                                if (Global._PqwIoCommon == null)
                                {
                                    await Task.Delay(1000, _commonIoSource.Token);
                                    continue;
                                }
                                Global._PqwIoCommon.GetDi();
                                if (Global._PqwIoCommon.GetDi((int)CommonIODefineDi.启动))
                                {
                                    if (!Global._isRunning)
                                    {
                                        StartUpCmd(new object());
                                    }
                                }
                                if (Global._PqwIoCommon.GetDi((int)CommonIODefineDi.复位))
                                {
                                    ResetCmd(new object());
                                }
                                if (!Global._PqwIoCommon.GetDi((int)CommonIODefineDi.急停))
                                {
                                    if (!Global._isEmg)
                                    {
                                        EmgStopCmd(new object());
                                    }
                                }
                                if (!Global._PqwIoCommon.GetDi((int)CommonIODefineDi.安全光幕))
                                {
                                    isSafeSunShine = true;
                                    if (Global._isRunning)
                                    {
                                        if (!Global._isEmg)
                                        {
                                            EmgStopCmd(new object());
                                        }
                                    }
                                }
                                else
                                {
                                    isSafeSunShine = false;
                                }
                                if (!Global._PqwIoCommon.GetDi((int)CommonIODefineDi.安全门))
                                {
                                    isSafeDoor = true;
                                    if (!Global._isEmg)
                                    {
                                        EmgStopCmd(new object());
                                    }
                                }
                                else
                                {
                                    isSafeDoor = false;
                                }
                            }
                            else
                            {
                                //线程被取消，退出线程
                                break;
                            }

                            await Task.Delay(150, _commonIoSource.Token);
                        }
                        catch (Exception e)
                        {
                            MyLog.Error(e);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MyLog.Error(ex);
                }
            }), _commonIoSource.Token);
        }

        /// <summary>
        /// 界面退出方法
        /// </summary>
        /// <param name="obj"></param>
        private void WindowClosingCmd(object obj)
        {
            _commonIoSource.Cancel();
        }

        /// <summary>
        /// 其他界面修改配置名
        /// </summary>
        /// <param name="name"></param>
        public void ChangeNowConfigNane(string name, string WorkStationName, string OrderName)
        {
            NowConfigName = name;
            NowConfigName = name + "，当前站名：" + Global._WorkStationName + ",当前工单：" + Global._WorkStationOrderName;
        }

        /// <summary>
        /// 初始化所有工位
        /// </summary>
        public void Init()
        {
            List<NewWorkStationModel> stations = new List<NewWorkStationModel>();
            for (int i = 0; i < Global._Config.MaxStationNums; i++)
            {
                int id = 0;
                if (Global._Config.MaxStationNums == 16)
                {
                    id = StationIdConver16(i + 1);
                }
                else if (Global._Config.MaxStationNums == 20)
                {
                    id = StationIdConver20(i + 1);
                }
                else if (Global._Config.MaxStationNums == 12)
                {
                    id = StationIdConver12(i + 1);
                }
                NewWorkStationModel newWork = new();
                newWork.Name = "工位" + (id).ToString();
                newWork.Result = "待测";
                newWork.StationTestId = id;
                newWork.IsExecute = false;
                newWork.ResultColor = _grayBrush;
                newWork.Code = "暂无二维码";
                newWork.Test1 = "1挡";
                newWork.Test2 = "2挡";
                newWork.Test3 = "3挡";
                newWork.StationTestRes = true;
                stations.Add(newWork);
            }
            Application.Current.Dispatcher.Invoke(() =>
            {
                WorkStations = new ObservableCollection<NewWorkStationModel>(stations);
            });
        }

        /// <summary>
        /// 改变工位检测状态
        /// </summary>
        /// <param name="obj"></param>
        private void ChangeStatus(object obj)
        {
            try
            {
            }
            catch (Exception e)
            {
                UpdateMessage(e.Message, LogLevel.Error);
            }
        }

        #endregion 绑定方法

        #region 通用方法

        private void UpdateMessage(string msg, LogLevel logLevel = LogLevel.Info)
        {
            Application.Current.Dispatcher.BeginInvoke(() =>
            {
                updatemessage?.Invoke(msg, logLevel);
            });
        }

        #endregion 通用方法
    }
}